#!/usr/bin/python3
# -*- coding: utf-8 -*-

from configparser import ConfigParser
from os import path
from subprocess import Popen
from sys import exit

from modules.api.base_translation import BaseTranslation
from modules.utils import MY_ERROR_CODES, get_file_encoding, print_err, print_warn

try:
    from google_trans_new import google_translator
except ImportError:
    print_err('未安装google_trans_new模块，即将开始安装，期间请勿进行其他操作！')
    subp = Popen(
        'pip3 install google_trans_new -i https://mirrors.aliyun.com/pypi/simple/',
        bufsize=-1,
    )
    subp.wait()
    if subp.poll() == 0:
        # 新部署的python环境里可能无requests模块。若找不到requests模块，则继续安装requests模块，否则google_trans_new模块无法正常使用
        try:
            from google_trans_new import google_translator
        except ImportError:
            subp2 = Popen(
                'pip3 install requests -i https://mirrors.aliyun.com/pypi/simple/',
                bufsize=-1,
            )
            subp2.wait()
            if subp2.poll() == 0:
                from google_trans_new import google_translator
    else:
        print_err('google_trans_new模块安装超时，请稍后重试！')
        subp.kill()
        exit(0)

# 所有支持的语种字典
_GOOGLE_COMMON_LANGS = ['auto', 'zh-cn', 'zh-tw', 'en', 'ja']

# 源语种字典
_GOOGLE_FROM_LANGS = {
    '1': {'n': '自动检测（推荐）', 'c': 'auto'},
    '2': {'n': '汉语（简体）', 'c': 'zh-cn'},
    '3': {'n': '汉语（繁体）', 'c': 'zh-tw'},
    '4': {'n': '英语', 'c': 'en'},
    '5': {'n': '日语', 'c': 'ja'},
}

# 常用目标语种字典
_GOOGLE_TO_LANGS = {
    '1': {'n': '汉语（简体）', 'c': 'zh-cn'},
    '2': {'n': '汉语（繁体）', 'c': 'zh-tw'},
    '3': {'n': '英语', 'c': 'en'},
    '4': {'n': '日语', 'c': 'ja'},
}

# 初始化谷歌翻译API
_translator = google_translator()


class GoogleTranslation(BaseTranslation):
    '''
    谷歌翻译第三方API
    '''

    def __init__(self, section: str):

        BaseTranslation.__init__(self, section)
        self.section = section
        self._get_config()

    def translate(self, source_txt: str, to_lang: str, from_lang='auto') -> str:
        '''
        开始翻译

        - source_txt: 输入文本
        - to_lang: 目标语种
        - from_lang: 源语种
        '''

        # 当源语言不在受支持的语种范围内时，强制将源语言设置为auto，确保翻译能正常进行
        if not from_lang in _GOOGLE_COMMON_LANGS:
            from_lang = 'auto'
            print_warn('源语言不在受支持的语种范围内，已强制重置为“自动检测”！')

        # 当源语言不在受支持的语种范围内时，强制将源语言设置为zh-cn，确保翻译能正常进行
        if not to_lang in _GOOGLE_COMMON_LANGS:
            to_lang = 'zh-cn'
            print_warn('目标语言不在受支持的语种范围内，已强制重置为“汉语（简体）”！')

        if to_lang == from_lang:
            print_warn('目标语种和源语种相同。')
            return source_txt

        # 原文本长度超过上限
        if len(source_txt) > self._max_char:
            print_err(MY_ERROR_CODES['ERR_10002'])
            return 'ERR_10002'

        target = ''
        try:
            target = _translator.translate(
                source_txt, lang_tgt=to_lang, lang_src=from_lang
            )

        except Exception as e:
            print_err(f'翻译出现异常：{e.args[0]}！')
            target = 'ERR_10001'

        return target

    def _get_config(self):
        '''
        获取配置
        '''

        config_path = path.join(
            path.abspath('.'), 'modules', 'api', 'google', 'config.ini'
        )
        if not path.isfile(config_path):
            return

        conf = ConfigParser()  # 调用读取配置模块中的类
        conf.optionxform = lambda option: option
        conf.read(config_path, encoding=get_file_encoding(config_path))

        self._rate = conf.getint(self.section, 'rate')
        if self._rate < 1:
            self._rate = 1
        self._max_char = conf.getint(self.section, 'max_char')
        if self._max_char < 50:
            self._max_char = 2000

    def get_from_langs(self) -> dict:
        '''
        获取源语种字典
        '''
        return _GOOGLE_FROM_LANGS

    def get_to_langs(self) -> dict:
        '''
        获取目标语种字典
        '''
        return _GOOGLE_TO_LANGS
